<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="###Java OkHttp使用本文使用eclipse编辑器，gradle依赖jar，如若未配置此环境，请转Java Eclipse配置gradle编译项目配置好环境后再查看此文  在build.gradle中添加依赖compile &amp;#39;com.squareup.okhttp3:okhttp:3.8.1&amp;#39;">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Java-OkHttp使用">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Java/Java-OkHttp使用/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="###Java OkHttp使用本文使用eclipse编辑器，gradle依赖jar，如若未配置此环境，请转Java Eclipse配置gradle编译项目配置好环境后再查看此文  在build.gradle中添加依赖compile &amp;#39;com.squareup.okhttp3:okhttp:3.8.1&amp;#39;">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2018-08-06T10:45:51.676Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java-OkHttp使用">
<meta name="twitter:description" content="###Java OkHttp使用本文使用eclipse编辑器，gradle依赖jar，如若未配置此环境，请转Java Eclipse配置gradle编译项目配置好环境后再查看此文  在build.gradle中添加依赖compile &amp;#39;com.squareup.okhttp3:okhttp:3.8.1&amp;#39;">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Java/Java-OkHttp使用/"/>





  <title>Java-OkHttp使用 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Java/Java-OkHttp使用/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java-OkHttp使用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:39+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>###Java OkHttp使用<br><strong>本文使用eclipse编辑器，gradle依赖jar，如若未配置此环境，请转<a href="http://www.jianshu.com/p/2495ffc49caa" target="_blank" rel="noopener">Java Eclipse配置gradle编译项目</a>配置好环境后再查看此文</strong></p>
<ol>
<li>在build.gradle中添加依赖<br><code>compile &#39;com.squareup.okhttp3:okhttp:3.8.1&#39;</code></li>
</ol>
<a id="more"></a>
<ol start="2">
<li><p>同步Get请求</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 同步get请求</span><br><span class="line"> */</span><br><span class="line">public static void syncGet() throws Exception&#123;</span><br><span class="line">	String urlBaidu = &quot;http://www.baidu.com/&quot;;</span><br><span class="line">	OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象</span><br><span class="line">	Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求</span><br><span class="line">	Response response = okHttpClient.newCall(request).execute(); // 返回实体</span><br><span class="line">	if (response.isSuccessful()) &#123; // 判断是否成功</span><br><span class="line">		/**获取返回的数据，可通过response.body().string()获取，默认返回的是utf-8格式；</span><br><span class="line">		 * string()适用于获取小数据信息，如果返回的数据超过1M，建议使用stream()获取返回的数据，</span><br><span class="line">		 * 因为string() 方法会将整个文档加载到内存中。*/</span><br><span class="line">		System.out.println(response.body().string()); // 打印数据</span><br><span class="line">	&#125;else &#123;</span><br><span class="line">		System.out.println(&quot;失败&quot;); // 链接失败</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>异步Get请求</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 异步Get请求</span><br><span class="line"> */</span><br><span class="line">public static void asyncGet() &#123;</span><br><span class="line">	String urlBaidu = &quot;http://www.baidu.com/&quot;;</span><br><span class="line">	OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象</span><br><span class="line">	Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求</span><br><span class="line">	okHttpClient.newCall(request).enqueue(new Callback() &#123; // 回调 </span><br><span class="line">		</span><br><span class="line">		public void onResponse(Call call, Response response) throws IOException &#123;</span><br><span class="line">			// 请求成功调用，该回调在子线程</span><br><span class="line">			System.out.println(response.body().string());</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		public void onFailure(Call call, IOException e) &#123;</span><br><span class="line">			// 请求失败调用</span><br><span class="line">			System.out.println(e.getMessage());</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>4.Post提交表单<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Post提交表单</span><br><span class="line"> */</span><br><span class="line">public static void postFromParameters() &#123;</span><br><span class="line">	String url = &quot;http://v.juhe.cn/wepiao/query&quot;; // 请求链接</span><br><span class="line">	String KEY = &quot;9488373060c8483a3ef6333353fdc7fe&quot;; // 请求参数</span><br><span class="line">	OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象</span><br><span class="line">	RequestBody formBody = new FormBody.Builder().add(&quot;key&quot;, KEY).build(); // 表单键值对</span><br><span class="line">	Request request = new Request.Builder().url(url).post(formBody).build(); // 请求</span><br><span class="line">	okHttpClient.newCall(request).enqueue(new Callback() &#123;// 回调</span><br><span class="line"></span><br><span class="line">		public void onResponse(Call call, Response response) throws IOException &#123;</span><br><span class="line">			System.out.println(response.body().string());//成功后的回调</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		public void onFailure(Call call, IOException e) &#123;</span><br><span class="line">			System.out.println(e.getMessage());//失败后的回调</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol start="5">
<li><p>Post提交字符串</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Post提交字符串</span><br><span class="line"> * 使用Post方法发送一串字符串，但不建议发送超过1M的文本信息</span><br><span class="line"> */</span><br><span class="line">public static void postStringParameters()&#123;</span><br><span class="line">	MediaType MEDIA_TYPE = MediaType.parse(&quot;text/text; charset=utf-8&quot;);</span><br><span class="line">	String url = &quot;http://v.juhe.cn/wepiao/query&quot;; // 请求链接</span><br><span class="line">	OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象</span><br><span class="line">	String string = &quot;key=9488373060c8483a3ef6333353fdc7fe&quot;; // 要发送的字符串</span><br><span class="line">	/**</span><br><span class="line">	 * RequestBody.create(MEDIA_TYPE, string)</span><br><span class="line">	 * 第二个参数可以分别为：byte[]，byteString,File,String。</span><br><span class="line">	 */</span><br><span class="line">	Request request = new Request.Builder().url(url)</span><br><span class="line">				.post(RequestBody.create(MEDIA_TYPE,string)).build();</span><br><span class="line">	okHttpClient.newCall(request).enqueue(new Callback() &#123;</span><br><span class="line">		public void onResponse(Call call, Response response) throws IOException &#123;</span><br><span class="line">			System.out.println(response.body().string());</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">		public void onFailure(Call call, IOException e) &#123;</span><br><span class="line">			System.out.println(e.getMessage());</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>Gson解析Response的Gson对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Gson解析Response的Gson对象</span><br><span class="line"> */</span><br><span class="line">public static void gsonResponsePost() &#123;</span><br><span class="line">	String url = &quot;http://v.juhe.cn/wepiao/query&quot;; // 请求链接</span><br><span class="line">	String KEY = &quot;9488373060c8483a3ef6333353fdc7fe&quot;; // 请求参数</span><br><span class="line">	OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象</span><br><span class="line">	RequestBody formBody = new FormBody.Builder().add(&quot;key&quot;, KEY).build(); // 表单键值对</span><br><span class="line">	Request request = new Request.Builder().url(url).post(formBody).build(); // 请求</span><br><span class="line">	okHttpClient.newCall(request).enqueue(new Callback() &#123;// 回调</span><br><span class="line"></span><br><span class="line">		public void onResponse(Call call, Response response) throws IOException &#123;</span><br><span class="line">			//成功后的回调</span><br><span class="line">			Gson gson = new Gson();</span><br><span class="line">			Info info = gson.fromJson(response.body().string(), Info.class);</span><br><span class="line">			System.out.println(info.toString());</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		public void onFailure(Call call, IOException e) &#123;</span><br><span class="line">			System.out.println(e.getMessage());//失败后的回调</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br><span class="line">/**</span><br><span class="line"> * Java Bean</span><br><span class="line">	 */</span><br><span class="line">public class Info&#123;</span><br><span class="line">	int error_code; //状态码</span><br><span class="line">	String reason; // 返回状态文字</span><br><span class="line">	Result result; // 页面URL</span><br><span class="line">	@Override</span><br><span class="line">	public String toString() &#123;</span><br><span class="line">		return &quot;Info [error_code=&quot; + error_code + &quot;, reason=&quot; + reason + &quot;, result=&quot; + result.toString() + &quot;]&quot;;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">/**</span><br><span class="line"> * Java Bean</span><br><span class="line">	 */</span><br><span class="line">public class Result&#123;</span><br><span class="line">	String h5url;</span><br><span class="line">	String h5weixin;</span><br><span class="line">	@Override</span><br><span class="line">	public String toString() &#123;</span><br><span class="line">		return &quot;Result [h5url=&quot; + h5url + &quot;, h5weixin=&quot; + h5weixin + &quot;]&quot;;</span><br><span class="line">	&#125;	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>okhttp3 设置超时时间</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 设置超时</span><br><span class="line"> * @throws IOException </span><br><span class="line"> */</span><br><span class="line">public static void timeOutPost() throws IOException &#123;</span><br><span class="line">	OkHttpClient client = new OkHttpClient.Builder()</span><br><span class="line">						        .connectTimeout(10, TimeUnit.SECONDS)//设置链接超时</span><br><span class="line">						        .writeTimeout(10, TimeUnit.SECONDS) // 设置写数据超时</span><br><span class="line">						        .readTimeout(30, TimeUnit.SECONDS) // 设置读数据超时</span><br><span class="line">						        .build();</span><br><span class="line">	Request request = new Request.Builder().url(&quot;http://www.baidu.com/&quot;).build();</span><br><span class="line"></span><br><span class="line">	Response response = client.newCall(request).execute();</span><br><span class="line">	System.out.println(&quot;Response completed: &quot; + response);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>缓存设置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 缓存设置</span><br><span class="line"> * @throws Exception</span><br><span class="line"> */</span><br><span class="line">public static void cachePost() throws Exception &#123;</span><br><span class="line">	File sdcache = new File(&quot;D:/file&quot;);</span><br><span class="line">       int cacheSize = 10 * 1024 * 1024; // 10 MiB</span><br><span class="line">	OkHttpClient client = new OkHttpClient()</span><br><span class="line">			.Builder()</span><br><span class="line">			.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))</span><br><span class="line">			.build();</span><br><span class="line">	Request request = new Request.Builder()</span><br><span class="line">               .url(&quot;http://publicobject.com/helloworld.txt&quot;)</span><br><span class="line">               .build();</span><br><span class="line"></span><br><span class="line">       Response response1 = client.newCall(request).execute();</span><br><span class="line">       if (!response1.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response1);</span><br><span class="line"></span><br><span class="line">       String response1Body = response1.body().string();</span><br><span class="line">       System.out.println(&quot;Response 1 response:          &quot; + response1);</span><br><span class="line">       System.out.println(&quot;Response 1 cache response:    &quot; + response1.cacheResponse());</span><br><span class="line">       System.out.println(&quot;Response 1 network response:  &quot; + response1.networkResponse());</span><br><span class="line"></span><br><span class="line">       request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();</span><br><span class="line">       Response response2 = client.newCall(request).execute();</span><br><span class="line">       if (!response2.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response2);</span><br><span class="line"></span><br><span class="line">       String response2Body = response2.body().string();</span><br><span class="line">       System.out.println(&quot;Response 2 response:          &quot; + response2);</span><br><span class="line">       System.out.println(&quot;Response 2 cache response:    &quot; + response2.cacheResponse());</span><br><span class="line">       System.out.println(&quot;Response 2 network response:  &quot; + response2.networkResponse());</span><br><span class="line"></span><br><span class="line">       System.out.println(&quot;Response 2 equals Response 1? &quot; + response1Body.equals(response2Body));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>打印结果:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Response 1 response:          Response&#123;protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt&#125;</span><br><span class="line">Response 1 cache response:    Response&#123;protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt&#125;</span><br><span class="line">Response 1 network response:  null</span><br><span class="line">Response 2 response:          Response&#123;protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt&#125;</span><br><span class="line">Response 2 cache response:    null</span><br><span class="line">Response 2 network response:  Response&#123;protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt&#125;</span><br><span class="line">Response 2 equals Response 1? true</span><br></pre></td></tr></table></figure></p>
<ol start="9">
<li><p>复用OkHttpClient</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 所有HTTP请求的代理设置，超时，缓存设置等都需要在OkHttpClient中设置。 如果需要更改一个请求的配置，可以使用</span><br><span class="line"> * OkHttpClient.newBuilder()获取一个builder对象，</span><br><span class="line"> * 该builder对象与原来OkHttpClient共享相同的连接池，配置等。</span><br><span class="line"> */</span><br><span class="line">public static void shareClient() &#123;</span><br><span class="line">	OkHttpClient client = new OkHttpClient();</span><br><span class="line">	Request request = new Request.Builder().url(&quot;http://www.baidu.com/&quot;).build();</span><br><span class="line"></span><br><span class="line">	try &#123;</span><br><span class="line">		// Copy to customize OkHttp for this request.</span><br><span class="line">		OkHttpClient copy = client.newBuilder().readTimeout(500, TimeUnit.MILLISECONDS).build();</span><br><span class="line">		Response response = copy.newCall(request).execute();</span><br><span class="line">		System.out.println(&quot;Response 1 succeeded: &quot; + response);</span><br><span class="line">	&#125; catch (IOException e) &#123;</span><br><span class="line">		System.out.println(&quot;Response 1 failed: &quot; + e);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	try &#123;</span><br><span class="line">		// Copy to customize OkHttp for this request.</span><br><span class="line">		OkHttpClient copy = client.newBuilder().readTimeout(3000, TimeUnit.MILLISECONDS).build();</span><br><span class="line">		Response response = copy.newCall(request).execute();</span><br><span class="line">		System.out.println(&quot;Response 2 succeeded: &quot; + response);</span><br><span class="line">	&#125; catch (IOException e) &#123;</span><br><span class="line">		System.out.println(&quot;Response 2 failed: &quot; + e);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>OkHttp3处理验证</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 登录验证</span><br><span class="line"> * @throws IOException</span><br><span class="line"> */</span><br><span class="line">public static void authenticatorPost() throws IOException &#123;</span><br><span class="line">	OkHttpClient okHttpClient = </span><br><span class="line">			new OkHttpClient</span><br><span class="line">			.Builder()</span><br><span class="line">			.authenticator(new Authenticator() &#123;</span><br><span class="line">				</span><br><span class="line">				public Request authenticate(Route route, Response response) throws IOException &#123; </span><br><span class="line">					System.out.println(response.challenges().toString());</span><br><span class="line">					String credential = Credentials.basic(&quot;jesse&quot;, &quot;password1&quot;);</span><br><span class="line">					return response</span><br><span class="line">							.request()</span><br><span class="line">							.newBuilder()</span><br><span class="line">							.addHeader(&quot;Authorization&quot;, credential)</span><br><span class="line">							.build();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;)</span><br><span class="line">			.build();</span><br><span class="line">	Request request = new Request.Builder().url(&quot;http://publicobject.com/secrets/hellosecret.txt&quot;).build();</span><br><span class="line">	Response response = okHttpClient.newCall(request).execute();</span><br><span class="line">	if (!response.isSuccessful()) throw new IOException(&quot;Unexpected code &quot; + response);</span><br><span class="line"></span><br><span class="line">    System.out.println(response.body().string());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><a href="http://git.oschina.net/zaitingma/codes/tnwlcoq07h6yie59kdbrm26" target="_blank" rel="noopener">代码下载</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Java/Java-NIO学习使用/" rel="next" title="Java-NIO学习使用">
                <i class="fa fa-chevron-left"></i> Java-NIO学习使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Java/Java-Proxy动态代理/" rel="prev" title="Java-Proxy动态代理">
                Java-Proxy动态代理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
